# MakeBy: LiuBoyuan
import json
import os
from collections import defaultdict
from typing import Dict

from basic.entiys.point.Point import Point

ABS_PATH = r"Q:\常用程序\魔古大陆\魔古大陆 V1.0\V1.07\backend\backend\datas"
now_path = "./datas" if __name__ != '__main__' else ABS_PATH


class PointGetter:

    @staticmethod
    def get_file_json() -> dict:
        """
        加载文件的json数据
        :return:
        """
        with open(os.path.join(now_path, "mapper.json"), "r", encoding='utf-8') as f:
            return json.load(f)

    @staticmethod
    def apdot_to_web_json(json: Dict[str, dict] = None) -> dict:
        """
        将文件的json数据适配成前端可识别的json数据
        :param json: 文件json 默认读取一个新的
        :return: 前端可识别的json数据
        """

        def __default_child_mapper() -> Dict[str, list]:
            print("被调用")
            return {
                'city': [],
                'army': [],
                'block': []
            }

        city = "city"
        army = "army"
        block = "block"

        if json is None:
            json = PointGetter.get_file_json()

        web_json = defaultdict(__default_child_mapper)

        for _, map_value in json.items():
            temp_point = Point(**map_value)

            if temp_point.power is not None:  # 当前遍历点有势力存在
                temp_site = [temp_point.x, temp_point.y]
                power_name = temp_point.power
                if temp_point.city is not None:  # 当前点为 城市
                    temp_city = temp_point.city
                    web_json[power_name][city].append([temp_city, temp_site])
                elif temp_point.army != []:  # 当前点有军队存在
                    temp_army = temp_point.army
                    web_json[power_name][army].append([temp_army, temp_site])
                else:  # 就是一个有势力但是不存在任何特殊点的点
                    web_json[power_name][block].append(temp_site)

        return dict(web_json)

    @staticmethod
    def init() -> bool:
        """
        初始化地图数据
        :return:
        """
        mapper = {}
        for row in range(1, 31):
            for col in range(1, 31):
                name = str((row - 1) * 30 + col)
                mapper[name] = Point(row, col, None, None).to_json()
        file_path = os.path.join(now_path, "mapper.json")
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(mapper, f, ensure_ascii=True)
        print("[地图初始模块] 初始化完毕")


if __name__ == '__main__':
    # PointGetter.init()
    print(PointGetter.apdot_to_web_json())
